#!/usr/bin/env python
# Vort Rider: Riding the Vorterix the good way

from xml.etree.ElementTree import ElementTree
import re
from cStringIO import StringIO
import subprocess
import sys
import urllib2
import urlparse

def get_settings():
    settings = {}
    settings['base_url'] = 'http://www.vorterix.com/'
    settings['xml_url'] = settings['base_url'] + 'xml/'
    settings['video_player'] = 'mplayer'
    return settings


def get_text(tag, path):
    return tag.find(path).text.strip()


def get_main_sections():
    "Returns a list with the main XML (name, xmldata)"
    settings = get_settings()

    xml_sections = []
    xml_re = re.compile(r'\'[^\']+?\.xml\'|"[^"]+?\.xml"', re.IGNORECASE)
    main_page = urllib2.urlopen(settings['base_url']).read()
    for xml_name in xml_re.findall(main_page):
        xml_url = settings['base_url'] + xml_name.replace("'", '').replace('"', '')
        sec_name = xml_name[xml_name.rfind('/') + 1:xml_name.rfind('.')]
        try:
            xml_sections.append((sec_name, urllib2.urlopen(xml_url).read()))
        except urllib2.HTTPError, e:
            print 'Error buscando xml (%s)\n%s' % (xml_url, e)
    return xml_sections


def get_video_index():
    xml_url = get_settings()['xml_url']
    index_url = xml_url + 'videos_def.xml'
    print 'Buscando videos en (%s)' % index_url
    tree = ElementTree()
    tree.parse(urllib2.urlopen(index_url))
    videos = []
    for item in tree.getroot():
        videos.append(dict([(x.tag, x.text) for x in item]))
    return videos


def get_video_data(urlXML):
    "Downloads the xml file from url and extracts the data for the video"
    settings = get_settings()
    base_url = settings['base_url']
    tree = ElementTree()
    tree.parse(urllib2.urlopen(urlXML))
    data_tag = tree.getroot()
    data_map = [('url_alta', 'flvAlta'), ('url_baja', 'flvBaja'),
                ('nombre', 'nombre'), ('url_img', 'urlImagen'),
                ('width', 'width'), ('height', 'height'),
                ('duration', 'duration'), ('id', 'id')]
    return dict([(x, data_tag.findtext(y)) for x, y in data_map])


def parse_videos_def(rawdata):
    "Extract information from xml for `videos_def` section"
    settings = get_settings()
    base_url = settings['base_url']
    tree = ElementTree()
    tree.parse(StringIO(rawdata))
    data = {'items': []}
    for item in tree.getroot().findall('item'):
        urlXML = base_url + item.findtext('urlXMLVideo')
        data['items'].append({'titulo': item.findtext('titulo'),
                              'urlXML': urlXML})
    return data


def parse_publicidades(rawdata):
    "Extracts information from xml for `publicidades` section"
    settings = get_settings()
    base_url = settings['base_url']
    tree = ElementTree()
    tree.parse(StringIO(rawdata))
    data = {}
    items = []
    for item in tree.getroot().findall('item'):
        items.append({'nombre': item.findtext('nombre'),
                      'url_alta': item.findtext('flvAlta'),
                      'url_baja': item.findtext('flvBaja')})
    data['items'] = items
    return data


def parse_destacados(rawdata):
    "Extracts information from xml for `destacados` section"
    settings = get_settings()
    base_url = settings['base_url']
    tree = ElementTree()
    tree.parse(StringIO(rawdata))
    data = {}
    items = []
    for item in tree.getroot().findall('lista/item'):
        items.append({'texto': item.findtext('texto'),
                      'subtexto': item.findtext('subtexto'),
                      'url_img': base_url + item.findtext('urlImagen'),
                      'url_audio': base_url + item.findtext('urlAudio')})
    data['items'] = items
    return data


def parse_napolitano(rawdata):
    "Extracts information from xml for `napolitano` section"
    settings = get_settings()
    base_url = settings['base_url']
    tree = ElementTree()
    tree.parse(StringIO(rawdata))
    data = {}
    items = []
    for item in tree.getroot().findall('lista/item'):
        items.append({'picurl': item.findtext('pic'),
                      'song': item.findtext('song'),
                      'artist': item.findtext('artist'),
                      'url': base_url + item.findtext('url').strip('../')})
    data['items'] = items
    return data


def get_auditorio_items(section_id):
    "Get the item ids for all the items in the `auditorio` section"
    settings = get_settings()
    base_url = settings['base_url']
    id_re = re.compile(r'video\.php\?id=(\d+)')
    item_ids = []
    for l in urllib2.urlopen(base_url + 'php/auditorio.php?id=%s' % section_id).readlines():
        result = id_re.search(l)
        if result:
            item_ids.extend(result.groups())
    return set(item_ids)

def get_auditorio_video_item(item_id):
    "Get complete information about `auditorio` video item"
    settings = get_settings()
    base_url = settings['base_url']
    video_item_url = base_url + 'xml/video.xml.php?id=%s' % item_id
    fields_map = {'id': 'id',
                  'video_url': 'flvAlta',
                  'name': 'nombre',
                  'pic_url': 'urlFotoPreview',
                  'width': 'width',
                  'height': 'height',
                  'lenght': 'duration'}
    tree = ElementTree()
    tree.parse(urllib2.urlopen(video_item_url))
    xml_root = tree.getroot()
    video_item = {}
    for k, v in fields_map.items():
        video_item[k] = xml_root.findtext(v)
    video_item['video_url'] = base_url + video_item['video_url'][6:]   # removes '../../'
    return video_item


def __main__(argv=None):
    if argv is None:
        argv = sys.argv
    print 'Riding the Vorterix fast and clean'
    return 0
    

if __name__ == '__main__':
    sys.exit(__main__())
